import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router'

export const useAuthStore = defineStore('auth', () => {
  // 状态管理
  const token = ref<string | null>(localStorage.getItem('token') || null)
  const role = ref<number | null>(Number(localStorage.getItem('role')) || null)
  // userInfo 引用被注释掉，但仍保留localStorage存储功能

  // 设置认证信息
  const setAuth = (newToken: string, newRole: number, userData?: any) => {
    token.value = newToken
    role.value = newRole
    if(userData) localStorage.setItem('userInfo', JSON.stringify(userData))
    // 持久化存储
    localStorage.setItem('token', newToken)
    localStorage.setItem('role', String(newRole))
  }

  // 单独设置 token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 单独设置角色
  const setRole = (newRole: number) => {
    role.value = newRole
    localStorage.setItem('role', String(newRole))
  }

  // 清除认证信息
  const clearAuth = () => {
    token.value = null
    role.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('role')
    localStorage.removeItem('userInfo') // 保持清除逻辑完整
  }

  // 检查登录状态
  const isAuthenticated = () => !!token.value

  // 检查角色权限
  const hasRole = (requiredRole: number) => {
    return role.value === requiredRole
  }

  // 登出操作
  const logout = () => {
    clearAuth()
    router.push('/login')
  }

  return { 
    token, 
    role, 
    setAuth,
    setToken,
    setRole,
    clearAuth,
    isAuthenticated,
    hasRole,
    logout
  }
})